<template>
  <div class="bill-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">{{ pageTitle }}</h2>
    </div>

    <!-- 账单列表 -->
    <div class="bill-list" v-if="billTotalDetail.id">
      <div class="bill-card">
        <!-- 账单头部 -->
        <div class="bill-header">
          <div class="merchant-info">
            <h3 class="merchant-name">结算单明细表</h3>
          </div>
        </div>

        <!-- 企业信息 -->
        <div class="enterprise-info">
          <div class="info-row">
            <span class="label">账期:</span>
            <span class="value" style="font-size: 14px;font-weight: bold;color: red;">{{ billTotalDetail.billPeriod }}</span>
          </div>
          <div class="info-row">
            <span class="label">入驻企业:</span>
            <span class="value">{{ billTotalDetail.enterpriseName }}</span>
          </div>
          <div class="info-row">
            <span class="label">租凭面积:</span>
            <span class="value">{{ billTotalDetail.rentalArea ? `${billTotalDetail.rentalArea}㎡` : '无数据' }}</span>
          </div>
          <div class="info-row">
            <span class="label">企业邮箱:</span>
            <span class="value">{{ billTotalDetail.email || '无' }}</span>
          </div>
          <div class="info-row">
            <span class="label">地点位置:</span>
            <span class="value">{{ billTotalDetail.companyAddress }}</span>
          </div>
        </div>

        <!-- 费用明细表格 -->
        <div class="bill-table">
          <table class="fee-table">
            <thead>
              <tr>
                <th style="width: 20%">项目</th>
                <th style="width: 60%">当期用量/计费单价/分摊比例</th>
                <th style="width: 20%">金额</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="fee in billTotalDetail.detailList" :key="fee.groupName">
                <td class="fee-type">{{ fee.groupName }}</td>
                <td class="fee-details">{{ fee.details }}</td>
                <td class="fee-amount">¥{{ fee.feeAmount }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 账单汇总 -->
        <div class="bill-summary">
          <div class="summary-row">
            <span class="label">合计:</span>
            <span class="total-amount">¥{{ billTotalDetail.totalFeeAmount }}</span>
          </div>
          <div class="summary-row">
            <span class="label">收款方:</span>
            <span class="payee">{{ billTotalDetail.tenantName }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <p>暂无结算单数据</p>
      <p class="empty-tip">请从结算单管理页面点击"分享"按钮查看详情</p>
    </div>

    <!-- 端操作区域 -->
    <div v-if="isFromPC" class="web-operations">
      <!-- 邮箱输入框 -->
      <div class="email-input-section">
        <label class="email-label">企业邮箱:</label>
        <input 
          v-model="emailInput" 
          type="email" 
          class="email-input" 
          placeholder="请输入企业邮箱地址"
          @blur="validateEmail"
        />
        <span v-if="emailError" class="email-error">{{ emailError }}</span>
      </div>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button @click="copy" class="action-btn copy-btn">复制链接</button>
        <button @click="sendEmail" class="action-btn email-btn">发送邮件</button>
      </div>
    </div>

  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getSettleBillTotalDetail, sendSettleBillEmail } from '@/api/settle';
import { copyValue, getUsageUnit } from '@/utils/index';

const billTotalDetail = ref({
  id: null,
  tenantName: '',
  enterpriseName: '',
  rentalArea: undefined,
  email: '',
  companyAddress: '',
  billPeriod: '',
  detailList: [],
  totalFeeAmount: undefined
});

const pageTitle = ref('');
const router = useRouter();
const shareUrl = ref('');
const isFromPC = ref(false);
const emailInput = ref('');
const emailError = ref('');

// 页面加载
onMounted(() => {
  loadBillData();
});

// URL参数加载数据
const loadBillData = async () => {
  const urlParams = new URLSearchParams(window.location.search);
  const hashParams = new URLSearchParams(window.location.hash.split('?')[1] || '');
  const billId = urlParams.get('billId') || hashParams.get('billId');
  const from = urlParams.get('from') || hashParams.get('from');
  if (from && from === 'billTotal') {
    isFromPC.value = true;
  }
  if (billId) {
    // 生成链接
    const baseUrl = window.location.origin;
    const exportUrl = router.resolve({
      name: 'Export',
      query: {
        billId: billId
      }
    }).href;
    shareUrl.value = `${baseUrl}/${exportUrl}`;

    try {
      const response = await getSettleBillTotalDetail(Number(billId));
      if (response.success && response.data) {
        const data = response.data;
        data.id = billId;
        data.detailList = (data.detailList || []).map((item: any) => ({
          groupName: item.groupName,
          details: `${item.currentUsage || 0}${getUsageUnit(item.objectType)} / ${item.unitPrice || 0}元/ ${item.allocationRatio}%`,
          feeAmount: item.feeAmount
        }))
        billTotalDetail.value = data;
        emailInput.value = data.email
        pageTitle.value = data.tenantName
      } else {
        ElMessage.error(`获取结算单数据失败: ${response.msg || '未知错误'}`);
      }
    } catch (error) {
      ElMessage.error(`加载结算单数据异常: ${error.message || '网络错误'}`);
    }
  }
};

// 复制链接
const copy = async () => {
  copyValue(shareUrl.value, '链接已复制');
};

const validateEmail = () => {
  if (!emailInput.value) {
    emailError.value = '请输入企业邮箱地址';
    return false;
  }
  
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(emailInput.value)) {
    emailError.value = '请输入有效的邮箱地址';
    return false;
  }
  
  emailError.value = '';
  return true;
};

// 邮件
const sendEmail = async () => {
  // 检查邮箱输入框
  if (!validateEmail()) {
    return;
  }
  
  const enterpriseName = billTotalDetail.value.enterpriseName;
  const email = emailInput.value;
  console.log('由平台发送邮件到:', email, '企业名称:', enterpriseName);
  try {
    let requestData = {
      id: billTotalDetail.value.id,
      email: email,
      enterpriseName: enterpriseName,
      billPeriod: billTotalDetail.value.billPeriod,
      totalFeeAmount: billTotalDetail.value.totalFeeAmount,
      tenantName: billTotalDetail.value.tenantName,
      settleBillPageUrl: shareUrl.value,
    }
    const response = await sendSettleBillEmail(requestData);
    if (response.success) {
      ElMessage.success('发送邮件成功');
    } else {
      ElMessage.error(`发送邮件失败: ${response.msg || '未知错误'}`);
    }
  } catch (error) {
    ElMessage.error(`发送邮件异常: ${error.message || '网络错误'}，请稍后再试`);
  }
};

</script>

<style lang="scss" scoped>
.bill-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 5px;
  overflow-x: hidden;
  max-width: 480px;
  margin: 0 auto;
}

// 页面标题
.page-header {
  text-align: center;
  margin-bottom: 10px;
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  padding: 10px 12px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.2);
}

.page-title {
  color: white;
  font-size: 18px;
  font-weight: bold;
  margin: 0;
}


// 账单列表
.bill-list {
  display: flex;
  flex-direction: column;
    gap: 10px;
}

.bill-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
}

// 账单头部
.bill-header {
  padding: 10px 12px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.merchant-name {
  font-size: 16px;
  font-weight: bold;
  color: #2c3e50;
  margin: 0 0 5px 0;
  text-align: center;
}

.bill-period {
  font-size: 14px;
  color: #6c757d;
  
  @media (max-width: 480px) {
    font-size: 12px;
  }
}


// 企业信息
.enterprise-info {
  padding: 10px 12px;
  border-bottom: 1px solid #e9ecef;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  flex-wrap: wrap;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-weight: 600;
  color: #495057;
  min-width: auto;
  margin-right: 8px;
    font-size: 12px;
  flex-shrink: 0;
}

.value {
  color: #212529;
  font-size: 12px;
  flex: 1;
  text-align: right;
}

// 费用明细表格
.bill-table {
    padding: 8px 5px;
    overflow-x: hidden;
}

.fee-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
  table-layout: fixed;
    min-width: 100%;
}

.fee-table th,
.fee-table td {
  padding: 6px 4px;
  text-align: left;
  border: 1px solid #dee2e6;
  word-wrap: break-word;
  overflow: hidden;
  line-height: 1.3;
    font-size: 9px;
}

.fee-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #495057;
}

.fee-table td {
  color: #212529;
}

.fee-type {
  font-weight: 600;
  word-break: break-all;
}

.fee-details {
    word-break: break-all;
}

.fee-amount {
  text-align: right;
  font-weight: 600;
  color: #e74c3c;
}

// 账单汇总
.bill-summary {
  padding: 10px 12px;
  background: #f8f9fa;
  border-top: 2px solid #67c23a;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.total-amount {
  font-size: 14px;
  font-weight: bold;
  color: #e74c3c;
}

.payee {
  font-weight: 600;
  color: #495057;
  font-size: 12px;
}

// Web端操作区域样式
.web-operations {
  margin-top: 16px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

// 邮箱输入框样式
.email-input-section {
  margin-bottom: 16px;
}

.email-label {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #495057;
  margin-bottom: 8px;
}

.email-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
  
  &:focus {
    outline: none;
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
  
  &::placeholder {
    color: #c0c4cc;
  }
}

.email-error {
  display: block;
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
}

// 操作按钮样式
.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  flex: 1;
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  &:active {
    transform: translateY(0);
  }
}

.copy-btn {
  background: #67c23a;
  color: white;
  
  &:hover {
    background: #5daf34;
  }
  
  &:active {
    background: #529b2e;
  }
}

.email-btn {
  background: #409eff;
  color: white;
  
  &:hover {
    background: #337ecc;
  }
  
  &:active {
    background: #2b6cb0;
  }
}

// 空状态样式
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
  color: #909399;
  
  p {
    margin: 0 0 8px 0;
    font-size: 14px;
  }
  
  .empty-tip {
    font-size: 12px;
    color: #c0c4cc;
  }
}

</style>